﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace VPLink2013.Framework
{
    public static class VPLink2013XsltTransformHelper
    {
        public static string StringAfter(string Text)
        {
            string Separator = @"\";
            if (Text == null)
            {
                return string.Empty;
            }

            Text = Text.ToLower();

            int iPos = Text.IndexOf(Separator);
            if (iPos > 0)
            {
                return Text.Substring(iPos + Separator.Length);
            }
            return Text;
        }

        public static string GetTransform(string strXml, string strXslPath, string login, string pathTemp)
        {
            if (!System.IO.File.Exists(strXslPath))
            {
                return "File not exists : " + strXslPath;
            }

            string strPathTrace = pathTemp;
            string XmlTraceFile = login + @"\webpart " + ContextTrace.PrefixFileName + ".xml";

            if (Directory.Exists(pathTemp))
            {
                ContextTrace.EnsureFolderExist(strPathTrace);
                FileSerialization.TraceFile(strPathTrace + @"\" + XmlTraceFile, strXml);
            }

            ContextTrace.AddTrace("Debut chargement XML");
            XmlTextReader xtr = new XmlTextReader(new StringReader(strXml));
            XPathDocument xpd = new XPathDocument(xtr);
            xtr.Close();
            XPathNavigator nav = xpd.CreateNavigator();
            ContextTrace.AddTrace("Fin chargement XML");

            StringWriter sw = new StringWriter();
            string Html = string.Empty;
            try
            {
                XslCompiledTransform xslt = new XslCompiledTransform();
                ContextTrace.AddTrace("Debut chargement XSL : " + strXslPath);
                xslt.Load(strXslPath);
                ContextTrace.AddTrace("Fin chargement XSL, debut transformation");
                xslt.Transform(nav, null, sw);
                ContextTrace.AddTrace("Fin transformation XSL");
                Html = sw.ToString();
                ContextTrace.AddTrace("Fin HTML ToString");
            }
            catch (System.Xml.Xsl.XsltException exc)
            {
                ContextTrace.AddTrace("Erreur XSL : " + exc.Message + ".LineNumber:" + exc.LineNumber + ",LinePosition:" + exc.LinePosition);
            }
            catch (System.Exception exc2)
            {
                ContextTrace.AddTrace("Erreur XSL : " + exc2.Message);
            }
            return Html;
        }
    }
}
